<template>
  <NavBar />
  <div class="form-with-result-container">
    <!-- 工作流基本信息 -->
    <div class="workflow-header">
      <div class="workflow-logo" v-if="workflow.logo">
        <img :src="workflow.logo" :alt="workflow.name + ' logo'" />
      </div>
      <div class="workflow-info">
        <h1>{{ workflow.name }}</h1>
        <p class="workflow-description">{{ workflow.description }}</p>
        <div class="workflow-id">ID: {{ workflow.id }}</div>
      </div>
    </div>

    <!-- 简化版动态表单 -->
    <el-form ref="formRef" :model="formData" label-width="140px" class="dynamic-form">
      <!-- 使用v-for循环所有字段，v-if过滤只保留需要的类型 -->
      <el-form-item
        v-for="(field, index) in workflow.inputParams"
        :key="index"
        :label="field.label"
        :required="field.required"
        :prop="field.name"
      >
        <!-- 字符串类型 - 使用文本输入框 -->
        <el-input
          v-if="field.type === 'string'"
          v-model="formData[field.name]"
          :placeholder="`请输入${field.label}`"
          :maxlength="field.maxLength"
          clearable
        />

        <!-- 布尔类型 - 使用开关组件 -->
        <el-switch
          v-else-if="field.type === 'bool'"
          v-model="formData[field.name]"
          :active-text="field.activeText || '是'"
          :inactive-text="field.inactiveText || '否'"
        />

        <!-- 数字类型 - 使用数字输入框 -->
        <el-input-number
          v-else-if="field.type === 'number'"
          v-model="formData[field.name]"
          :min="field.min"
          :max="field.max"
          :step="field.step || 1"
          :placeholder="`请输入${field.label}`"
          controls-position="right"
        />

        <!-- 字段描述信息 -->
        <div class="field-description" v-if="field.description">
          {{ field.description }}
          <span class="required-mark" v-if="field.required"> *必填</span>
        </div>
      </el-form-item>

      <!-- 表单操作按钮 -->
      <el-form-item class="form-actions">
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          执行工作流
        </el-button>
        <el-button @click="resetForm" :disabled="submitting"> 重置 </el-button>
      </el-form-item>
    </el-form>

    <!-- 结果展示区域 -->
    <div
      v-if="executionResult"
      class="result-container"
      :class="{ 'with-result': executionResult }"
    >
      <el-card>
        <div slot="header" class="result-header">
          <h2>执行结果</h2>
          <el-button type="text" icon="Close" @click="clearResult" class="close-result" />
        </div>

        <!-- 加载状态 -->
        <div v-if="loadingResult" class="result-loading">
          <el-loading-spinner />
          <p>正在加载结果...</p>
        </div>

        <!-- Markdown结果展示 -->
        <div v-else class="markdown-content" v-html="renderedMarkdown"></div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import NavBar from "@/components/home/NavBar.vue";
import { ref, reactive, onMounted, computed, onUnmounted } from "vue";
import { ElMessage, ElLoading } from "element-plus";
import MarkdownIt from "markdown-it";
import "github-markdown-css"; // 引入GitHub风格的Markdown样式

// 初始化Markdown渲染器
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  breaks: true,
});

// 工作流数据
const workflow = ref({
  id: "workflow_123",
  name: "基础信息处理工作流",
  description: "这是一个仅处理基础数据类型的工作流",
  logo: "https://picsum.photos/80/80?random=1",
  inputParams: [
    {
      name: "username",
      label: "用户名",
      description: "请输入用户登录名称",
      type: "string",
      required: true,
      maxLength: 20,
    },
    {
      name: "age",
      label: "年龄",
      description: "请输入用户年龄",
      type: "number",
      required: true,
      min: 0,
      max: 150,
      step: 1,
    },
    {
      name: "score",
      label: "评分",
      description: "请输入评分（保留一位小数）",
      type: "number",
      required: false,
      min: 0,
      max: 10,
      step: 0.1,
    },
    {
      name: "isVip",
      label: "是否VIP用户",
      description: "标记用户是否为VIP",
      type: "bool",
      required: false,
      defaultValue: false,
      activeText: "VIP",
      inactiveText: "普通",
    },
    {
      name: "email",
      label: "电子邮箱",
      description: "请输入用户电子邮箱地址",
      type: "string",
      required: false,
      maxLength: 50,
    },
    {
      name: "balance",
      label: "账户余额",
      description: "请输入账户初始余额",
      type: "number",
      required: true,
      min: 0,
      step: 10,
    },
    {
      name: "isActive",
      label: "是否激活",
      description: "账户是否已激活",
      type: "bool",
      required: true,
      defaultValue: true,
    },
    {
      name: "nickname",
      label: "昵称",
      description: "请输入用户昵称",
      type: "string",
      required: false,
      maxLength: 30,
    },
  ],
});

// 表单数据存储
const formData = reactive({});

// 表单引用
const formRef = ref(null);

// 状态管理
const submitting = ref(false);
const executionResult = ref(null);
const loadingResult = ref(false);
const renderedMarkdown = computed(() => {
  if (executionResult.value) {
    return md.render(executionResult.value);
  }
  return "";
});

// 初始化表单数据
const initFormData = () => {
  workflow.value.inputParams.forEach((field) => {
    // 只处理我们需要的三种类型
    if (["string", "bool", "number"].includes(field.type)) {
      // 根据类型设置默认值
      if (formData[field.name] === undefined) {
        if (field.defaultValue !== undefined) {
          formData[field.name] = field.defaultValue;
        } else {
          switch (field.type) {
            case "string":
              formData[field.name] = "";
              break;
            case "bool":
              formData[field.name] = false;
              break;
            case "number":
              formData[field.name] = 0;
              break;
          }
        }
      }
    }
  });
};

// 表单验证规则生成
const getValidationRules = () => {
  const rules = {};

  workflow.value.inputParams.forEach((field) => {
    if (["string", "bool", "number"].includes(field.type) && field.required) {
      rules[field.name] = [
        {
          required: true,
          message: `请${
            field.type === "string" ? "输入" : field.type === "number" ? "输入" : "选择"
          }${field.label}`,
          trigger: field.type === "bool" ? "change" : "blur",
        },
      ];

      // 数字类型的范围验证
      if (field.type === "number") {
        if (field.min !== undefined || field.max !== undefined) {
          rules[field.name].push({
            validator: (rule, value, callback) => {
              if (value === null || value === undefined) {
                return callback();
              }

              if (field.min !== undefined && value < field.min) {
                return callback(new Error(`最小值为${field.min}`));
              }

              if (field.max !== undefined && value > field.max) {
                return callback(new Error(`最大值为${field.max}`));
              }

              callback();
            },
            trigger: "blur",
          });
        }
      }
    }
  });

  return rules;
};

// 模拟执行工作流并获取结果
const executeWorkflow = async (params) => {
  // 模拟API请求延迟
  return new Promise((resolve) => {
    setTimeout(() => {
      // 构建Markdown格式的结果
      const result = `# 工作流执行结果

## 基本信息
- 工作流名称: ${workflow.value.name}
- 工作流ID: \`${workflow.value.id}\`
- 执行时间: ${new Date().toLocaleString()}
- 状态: **成功**

## 输入参数详情

| 参数名 | 类型 | 值 |
|--------|------|-----|
${Object.entries(params)
  .map(([key, value]) => {
    // 找到对应的字段信息
    const field = workflow.value.inputParams.find((f) => f.name === key);
    return `| ${field?.label || key} | ${field?.type} | \`${value}\` |`;
  })
  .join("\n")}

## 处理结果
工作流已成功执行，基于提供的参数完成了以下操作：

1. 验证了用户信息的完整性
2. 计算了用户的基础评分：${(params.score || 5) * 10}分
3. 设置了初始账户余额：¥${params.balance}
4. 标记用户状态为：${params.isActive ? "已激活" : "未激活"}

## 下一步建议
- ${params.isVip ? "VIP用户可享受专属服务" : "升级为VIP用户以享受更多服务"}
- 完善个人资料可提高账户安全性
- 定期登录可获取积分奖励`;

      resolve(result);
    }, 1500);
  });
};

// 表单提交处理
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    submitting.value = true;
    loadingResult.value = true;
    executionResult.value = null;

    // 执行表单验证
    // await formRef.value.validate(getValidationRules());

    // 构造提交数据
    const submitData = {
      workflowId: workflow.value.id,
      params: formData,
    };

    // 执行工作流并获取结果
    const result = await executeWorkflow(submitData.params);
    executionResult.value = result;

    ElMessage.success("工作流执行成功！");
  } catch (error) {
    console.error("表单验证失败:", error);
    ElMessage.error("请完善表单信息后再提交");
  } finally {
    submitting.value = false;
    loadingResult.value = false;
  }
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  executionResult.value = null;
  initFormData();
  ElMessage.info("表单已重置");
};

// 清除结果
const clearResult = () => {
  executionResult.value = null;
};

// 页面加载时初始化表单
onMounted(() => {
  initFormData();
});

// 组件卸载时清理
onUnmounted(() => {
  executionResult.value = null;
});
</script>

<style scoped>
.form-with-result-container {
  max-width: 900px;
  margin: 20px auto;
  padding: 60px 20px 20px 20px;
}

.workflow-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.workflow-logo {
  width: 64px;
  height: 64px;
  margin-right: 16px;
  border-radius: 6px;
  overflow: hidden;
}

.workflow-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.workflow-info h1 {
  margin: 0 0 8px 0;
  font-size: 20px;
  color: #333;
}

.workflow-description {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.workflow-id {
  font-size: 12px;
  color: #999;
  background-color: #f5f7fa;
  padding: 3px 8px;
  border-radius: 4px;
  display: inline-block;
}

.dynamic-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  gap: 10px;
}

.field-description {
  margin-top: 6px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.required-mark {
  color: #f56c6c;
}

/* 结果展示样式 */
.result-container {
  margin-top: 30px;
  transition: all 0.3s ease;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-header h2 {
  margin: 0;
  font-size: 18px;
}

.close-result {
  color: #909399;
  transition: color 0.2s;
}

.close-result:hover {
  color: #f56c6c;
}

.markdown-content {
  padding: 20px 0;
  font-size: 14px;
  line-height: 1.8;
}

/* 引入github-markdown-css后的样式补充 */
.markdown-content .markdown-body {
  box-sizing: border-box;
  min-width: 200px;
  max-width: 980px;
  margin: 0 auto;
  padding: 45px;
}

@media (max-width: 767px) {
  .markdown-content .markdown-body {
    padding: 15px;
  }
}

.result-loading {
  text-align: center;
  padding: 40px 0;
  color: #666;
}

.result-loading .el-loading-spinner {
  margin: 0 auto 16px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .form-with-result-container {
    padding: 10px;
  }

  .workflow-header {
    flex-direction: column;
  }

  .workflow-logo {
    margin-bottom: 12px;
    margin-right: 0;
  }
}
</style>
